<template>
  <div class="stats-view">
    <h1>程序使用量统计</h1>
    <div class="filter-row">
      <input v-model="start" type="date" class="date-input" />
      <span>至</span>
      <input v-model="end" type="date" class="date-input" />
      <button @click="loadStats" class="btn btn-primary">查询</button>
    </div>
    <div ref="chartRef" class="chart"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'

const start = ref('')
const end = ref('')
const chartRef = ref<HTMLDivElement | null>(null)
let chart: echarts.ECharts | null = null

const stats = ref<{ tool_name: string, count: number }[]>([])

async function loadStats() {
  const params = new URLSearchParams()
  if (start.value) params.append('start', start.value)
  if (end.value) params.append('end', end.value)
  const res = await fetch('http://localhost:3000/api/userlogs/stats?' + params.toString())
  const data = await res.json()
  if (data.success && data.data) {
    stats.value = data.data
    await nextTick()
    renderChart()
  } else {
    stats.value = []
    await nextTick()
    renderChart()
  }
}

function renderChart() {
  if (!chartRef.value) return
  if (!chart) chart = echarts.init(chartRef.value)
  if (!stats.value.length) {
    chart.clear()
    chart.setOption({
      title: { text: '暂无数据', left: 'center', top: 'center', textStyle: { fontSize: 20, color: '#888' } }
    })
    return
  }
  const option = {
    tooltip: {},
    xAxis: {
      type: 'category',
      data: stats.value.map(item => item.tool_name),
      axisLabel: { rotate: 30 }
    },
    yAxis: { type: 'value', name: '使用量' },
    series: [{
      type: 'bar',
      data: stats.value.map(item => item.count),
      itemStyle: { color: '#5470c6' }
    }]
  }
  chart.setOption(option, true)
}

onMounted(() => {
  loadStats()
  window.addEventListener('resize', resizeChart)
})

function resizeChart() {
  if (chart) chart.resize()
}

watch([start, end], () => {
  // 可选：自动刷新
  // loadStats()
})

// 保证页面卸载时销毁图表实例，防止内存泄漏
import { onBeforeUnmount } from 'vue'
onBeforeUnmount(() => {
  if (chart) chart.dispose()
  window.removeEventListener('resize', resizeChart)
})
</script>

<style scoped>
.stats-view {
  max-width: 900px;
  margin: 40px auto;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
  padding: 32px 24px;
}
.stats-view h1 {
  text-align: center;
  margin-bottom: 32px;
}
.filter-row {
  display: flex;
  align-items: center;
  gap: 12px;
  justify-content: center;
  margin-bottom: 32px;
}
.date-input {
  height: 38px;
  font-size: 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 0 10px;
}
.chart {
  width: 100%;
  height: 400px;
}
.btn-primary {
  background: #5470c6;
  color: #fff;
  border: none;
  border-radius: 4px;
  padding: 8px 24px;
  font-size: 16px;
  cursor: pointer;
}
.btn-primary:hover {
  background: #405a99;
}
</style> 